package org.example;

import java.io.*;
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import java.util.function.BiFunction;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class regexredux {

    public static void main(String[] args) throws IOException {
        // 读取dna.txt文件内容
        String input = readFile("/Users/huawei/IdeaProjects/java_cases_for_performance/src/main/java/org/example/dna.txt");

        final int initialLength = input.length();

        // 移除FASTA格式的标题行和所有换行符，保留纯序列
        final String sequence = input.replaceAll(">.*\n|\n", "");
        final int codeLength = sequence.length();

        // 定义需要匹配的正则表达式变体
        final List<String> variants = Arrays.asList(
                "agggtaaa|tttaccct",
                "[cgt]gggtaaa|tttaccc[acg]",
                "a[act]ggtaaa|tttacc[agt]t",
                "ag[act]gtaaa|tttac[agt]ct",
                "agg[act]taaa|ttta[agt]cct",
                "aggg[acg]aaa|ttt[cgt]ccct",
                "agggt[cgt]aa|tt[acg]accct",
                "agggta[cgt]a|t[acg]taccct",
                "agggtaa[cgt]|[acg]ttaccct"
        );

        // 并行计算每个正则表达式的匹配次数
        BiFunction<String, String, Entry<String, Long>> countMatcher = (variant, seq) -> {
            long count = Pattern.compile(variant).splitAsStream(seq).count() - 1;
            return new SimpleEntry<>(variant, count);
        };

        final Map<String, Long> results = variants.parallelStream()
                .map(variant -> countMatcher.apply(variant, sequence))
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

        // 输出每个正则表达式的匹配结果
        variants.forEach(variant -> System.out.println(variant + " " + results.get(variant)));

        // 定义替换规则（保持顺序）
        final Map<String, String> replacements = new LinkedHashMap<>();
        replacements.put("tHa[Nt]", "<4>");
        replacements.put("aND|caN|Ha[DS]|WaS", "<3>");
        replacements.put("a[NSt]|BY", "<2>");
        replacements.put("<[^>]*>", "|");
        replacements.put("\\|[^|][^|]*\\|", "-");

        // 执行替换操作
        String buf = sequence;
        for (Entry<String, String> entry : replacements.entrySet()) {
            buf = Pattern.compile(entry.getKey()).matcher(buf).replaceAll(entry.getValue());
        }

        // 输出长度信息
        System.out.println();
        System.out.println(initialLength);
        System.out.println(codeLength);
        System.out.println(buf.length());
    }

    // 读取文件内容的工具方法
    private static String readFile(String filename) throws IOException {
        // 使用try-with-resources确保流自动关闭
        try (InputStream is = new FileInputStream(filename);
             BufferedReader br = new BufferedReader(new InputStreamReader(is, "US-ASCII"))) {

            StringBuilder sb = new StringBuilder();
            String line;
            // 逐行读取文件内容
            while ((line = br.readLine()) != null) {
                sb.append(line).append('\n'); // 保留原换行符用于后续处理
            }
            // 移除最后多余的换行符（如果需要严格匹配原逻辑）
            if (sb.length() > 0) {
                sb.setLength(sb.length() - 1);
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            // 处理文件未找到的情况
            System.err.println("错误：未找到文件 '" + filename + "'，请确保文件存在于程序运行目录");
            throw e; // 重新抛出异常终止程序
        }
    }
}